package com.nowcoder.community.aspect;

import com.nowcoder.community.util.RedisKeyUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class RedisUserAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    @Pointcut("execution(* com.nowcoder.community.dao.UserMapper.update*(..))")
    public void pointCut() {}

    @Around("pointCut()")
    public Object afterUpdateUserInfo(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] params = joinPoint.getArgs();
        Object userId = params[0];

        Object result = null;

        try {
            // 继续执行update逻辑
            result = joinPoint.proceed();
        } catch (Exception e) {
            throw new RuntimeException("用户数据更新失败!");
        }

        int id = (int) userId;
        String redisKey = RedisKeyUtil.getUserKey(id);
        redisTemplate.opsForValue().getOperations().delete(redisKey);
        return result;
    }

}
